package com.jdone.compus.controller;


import com.jdone.compus.dto.ApiResponse;
import com.jdone.compus.dto.LoginRequest;
import com.jdone.compus.dto.RegisterRequest;
import com.jdone.compus.dto.JwtAuthenticationResponse;
import com.jdone.compus.model.User;
import com.jdone.compus.repository.UserRepository;
import com.jdone.compus.security.JwtTokenProvider;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Collections;
import java.util.UUID;

@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
@Api(value = "后台用户管理", tags = "用户管理、登录、注册等")
public class AuthController {

    private final UserRepository userRepository;
    private final JwtTokenProvider tokenProvider;

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public ApiResponse registerUser(@RequestBody RegisterRequest req) {
        if (userRepository.existsByUsername(req.getUsername())) {
            return ApiResponse.error("用户名已被占用");
        }
        if (userRepository.existsByEmail(req.getEmail())) {
            return ApiResponse.error("邮箱已被使用");
        }

        String salt = UUID.randomUUID().toString();
        String sha256 = DigestUtils.sha256Hex(req.getPassword() + salt);

        User user = new User();
        user.setUsername(req.getUsername());
        user.setEmail(req.getEmail());
        user.setSalt(salt);
        user.setPasswordHash(sha256);
        userRepository.save(user);
        return ApiResponse.success("注册成功");
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public ApiResponse authenticateUser(@RequestBody LoginRequest req) {
        User user = userRepository
                .findByUsernameOrEmail(req.getUsernameOrEmail(), req.getUsernameOrEmail())
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.UNAUTHORIZED, "用户不存在"));

        // **不要 Base64 解码**，直接使用前端传来的明文密码
        String attempt = req.getPassword() + user.getSalt();
        String sha256 = DigestUtils.sha256Hex(attempt);
        if (!sha256.equals(user.getPasswordHash())) {
            return ApiResponse.error("用户名或密码不正确");
        }

        // 生成 JWT 并返回
        String jwt = tokenProvider.generateToken(
                new UsernamePasswordAuthenticationToken(user.getUsername(), null, Collections.emptyList())
        );
        return new ApiResponse(true, "登录成功", new JwtAuthenticationResponse(jwt));
    }
}


